import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/user/login.vue'
import layout from '@/views/layout.vue'
import home from '@/views/home/home.vue'
import movie from '@/views/movie/movie.vue'
import qa from '@/views/QA/qa.vue'
import user from '@/views/user/user.vue'
import edit from '@/views/user/edit.vue'
import notfound from '@/views/notfound/notfound.vue'
import article from '@/views/home/article.vue'
import student from '@/views/user/student.vue'
import search from '@/views/home/search.vue'
import searchResult from '@/views/home/searchResult.vue'

Vue.use(VueRouter)

const routes = [
  {
    name: 'login',
    path: '/login',
    component: login,
  },
  {
    name:'layout',
    path: '/',
    component: layout,
    children: [
      {
        path: '/home',
        component: home
      },
      {
        name: 'movie',
        path: '/movie',
        component: movie,
      },
      {
        name: 'qa',
        path: '/qa',
        component: qa,
      },
      {
        name: 'user',
        path: '/user',
        component: user,
        meta: { isLogin:true }
      },
    ]
  },
  {
    name: 'myarticle',
    path: '/article',
    component: article,
  },
  {
    name: 'edit',
    path: '/edit',
    component: edit,
  },
  {
    path: '/notfound',
    component: notfound,
    meta: { showTab: true }
  },{
    name:"student",
    path: '/student',
    component: student,
  },{
    name:"search",
    path: '/search',
    component: search,
  },{
    name:"searchResult",
    path: '/searchResult',
    component: searchResult,
  },
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '*',
    redirect: '/notfound'
  }
]

/* 去掉路由跳转reject异常提示
注意：我们是直接修改VueRouter的原型，所以需要在实例化之前调用
*/
//(1)先保存路由原型链中默认的跳转函数
const originalPush = VueRouter.prototype.push
//(2)替换原型链中的push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    // 正常执行
    //originalPush.call() : 我们自定义的push底层还是调用默认的push
    return originalPush.call(this, location, onResolve, onReject)
  }
  //如果有异常，本来这个err默认是抛出的，我们直接不做任何处理（给吞掉了）
  /* 
  底层默认是抛出异常：err => {throw err}
  我们不抛出，不做任何处理：err => err
  */
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes
})

//导入token工具包
import { getToken } from '@/utils/token.js'
import { Toast } from 'vant';

// 注册导航守卫 (全局前置守卫  跳转之前执行)
router.beforeEach((to, from, next) => {
  //判断用户没有没有登录
  if (to.meta.isLogin && !getToken()) {
    /* this.$toast只能在组件里面使用,全局使用直接Toast即可（官网文档有介绍） */
    Toast.fail('请先登录')
    //没有登录，则跳转登录页
    next({ path: '/login' })
  } else {
    //有登录，正常跳转
    next()
  }
})

export default router
